/**
 * 
 */
package com.airnews.ticket.ui.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.airnews.ticket.R;
import com.airnews.ticket.model.FlightOrder;
import com.airnews.ticket.model.OrderInfo;
import com.airnews.ticket.model.OrderInfoResult;
import com.airnews.ticket.model.SearchOrder;
import com.airnews.ticket.net.WebAccessor;
import com.airnews.ticket.ui.BaseActivity;
import com.airnews.ticket.ui.Main;
import com.airnews.ticket.util.AddrUtil;
import com.airnews.ticket.util.DateUtil;
import com.airnews.ticket.util.FlyUtil;
import com.mobclick.android.MobclickAgent;

/**
 * @author luoxz
 *
 */
public class OrderList extends BaseActivity implements AdapterView.OnItemClickListener, OnClickListener {
	
	/** 是否需要更新数据，从详细页面返回时需要更新数据 */
	public static boolean UPDATE_INDICATOR = false;
	
	public final int NORESULT = 1;
	public final int SEARCH_ERROR=2;
	public final int SUCCESS=3;
	public final int ORDER_TIME = 4;
	public final int ORDER_PRICE = 5;
	
	public static List<OrderInfo> orderist = new ArrayList<OrderInfo> ();
	
	public SimpleAdapter sa;
	
	private final static int DATE_DIALOG = 0;
	private final static int TIME_DIALOG = 1;
	
	List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	
	private TextView orderScoll, btn_returnInput, bookOrderType, orderTimeStart, orderTimeEnd;
	private ListView orderList;
	private Button btnByTime, btnByPrice;
	
	private Button backBut;
	
	String[] selectOptionList = null;
	
	private Calendar c = null;
	
	private ProgressDialog progressDialog = null;
	
	public static SearchOrder searchOrder;
	
	private AddrUtil addrUtil;
	
	private FlyUtil flyUtil;
	
	private SharedPreferences sp;
	private String loginNameRe = "";
	private String isLoninOK = null;//是否登录
	private String autoLogin = null;//记着登录
	private Toast toast;
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_list);
		
		activityList.add(this); 
		
		backBut = (Button) findViewById(R.id.backBut);
		backBut.setOnClickListener(clickListener);
		
		sp = getSharedPreferences("UserInfoB2C", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
		
//		searchOrder = (SearchOrder)getIntent().getSerializableExtra("searchOrder");
		
		orderList = (ListView) findViewById(R.id.orderList);
		orderList.setOnItemClickListener(this);
		
		btnByTime = (Button) findViewById(R.id.btn_byTime);
		btnByTime.setOnClickListener(clickListener);
		btnByPrice = (Button) findViewById(R.id.btn_byPrice);
		btnByPrice.setOnClickListener(clickListener);
		
		findViewById(R.id.btn_reflush).setOnClickListener(clickListener);
		
		//初始化地址参数
		addrUtil = new AddrUtil(this);
		//初始化航空参数
		flyUtil = new FlyUtil(this);
		
		if (orderist.isEmpty()) {
			search();
		} else {
			renderData();
		}
		
	}
	
//	@Override
//    protected void onResume() {
//    	super.onResume();
//    	//回到后重新下载
//    	if (UPDATE_INDICATOR) {
//    		search();
//    		UPDATE_INDICATOR = false;
//    	}
//    }
	
    
	OnClickListener clickListener= new OnClickListener() { 
    	public void onClick(View v) { 
    		switch (v.getId()) {
    		case R.id.orderScoll: {//订单范围
    			selectOptionList=new String[]{"全部机票","国内机票","国际机票"};
    	          new AlertDialog.Builder(OrderList.this)
    	            .setTitle("选择")
    	            .setItems(
    	            		selectOptionList,
    	            		new DialogInterface.OnClickListener() {
		    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
		    	            	  orderScoll.setText(selectOptionList[whichcountry]);
		    	              }
		    	            })
    	            .setNegativeButton(
    	            		"取消", 
    	            		new DialogInterface.OnClickListener() { 
		    	              public void onClick(DialogInterface d, int which) { 
		    	                d.dismiss(); 
		    	              }
		    	            })
    	            .show();
    	          break;
    			}
    		case R.id.btn_byTime: {
    			Log.i("OrderList", "btn_byTime");
    			//调用
				Message msg = new Message();
				msg.what = ORDER_TIME;
				myHandler.sendMessage(msg);
    			break;
    		}
    		case R.id.btn_byPrice: {
    			Log.i("OrderList", "btn_byPrice");
    			//排序
    			Message msg = new Message();
				msg.what = ORDER_PRICE;
				myHandler.sendMessage(msg);
    			break;
    		}
    		case R.id.backBut: {
    			Intent intent = new Intent(OrderList.this, Main.class);
    			OrderList.UPDATE_INDICATOR = true;
    			startActivity(intent);
    			break;
    		}
    		case R.id.btn_reflush: {
    			searchOrder = new SearchOrder();
    			search();
    			break;
    		}
    		}
    	}
	};
	
	
	public Handler myHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NORESULT:
				toast = Toast.makeText(OrderList.this, "未找到符合条件的订单", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				data.clear();
				if (sa != null) {
					sa.notifyDataSetChanged();
				}
				break;
			case SEARCH_ERROR:
				toast = Toast.makeText(OrderList.this, (String)msg.obj, Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				data.clear();
				if (sa != null) {
					sa.notifyDataSetChanged();
				}
				break;
			case SUCCESS:
				renderData();
				break;
			case ORDER_TIME:
				//日期排序
    			Collections.sort(orderist, new Comparator<OrderInfo>() {
    			      public int compare(OrderInfo object1,
    			    		  OrderInfo object2) {
    			    	  	//根据日期倒序排序
    			    	   String[] result1 = object1.TicketOrders.get(0).FlightID.split(" ");
    					   String departureDate1 = result1[3];
    					   String[] result2 = object2.TicketOrders.get(0).FlightID.split(" ");
    					   String departureDate2 = result2[3];
    					   System.out.println("departureDate1="+departureDate1);
    					   System.out.println("departureDate2="+departureDate2);
//    			    	   String departureTime1 = departureDate1.substring(11,16);
//    			    	   String departureTime2 = departureDate2.substring(11,16);
//    			    	   Log.i("OrderList", "departureTime1:"+departureTime1+" departureTime2:"+departureTime2);
//    			    	   if (departureTime1 != "" && departureTime2 != "") {
//    			    		   if (DateUtil.compareTo(departureTime1, departureTime2)) {
//        			    		   return 1;
//        			    	   }
//    			    	   }
    			    	   
    			    	   if (departureDate1 != "" && departureDate2 != "") {
    			    		   if (DateUtil.compareTo(departureDate1, departureDate2)) {
        			    		   return 1;
        			    	   }
    			    	   }
    			    	   
    			    	   return -1;
    			      }    
    			     }); 
    			renderData();
				break;
			case ORDER_PRICE:
				//价格排序
    			Collections.sort(orderist, new Comparator<OrderInfo>() {
    			      public int compare(OrderInfo object1,
    			    		  OrderInfo object2) {
    			    	  	//根据价格顺排排序
    			    	   String cabinPrice1 = object1.TicketOrders.get(0).CabinPrice;
    			    	   String cabinPrice2 = object2.TicketOrders.get(0).CabinPrice;
    			    	   Log.i("OrderList", "cabinPrice1:"+cabinPrice1+" cabinPrice2:"+cabinPrice2);
    			    	   BigDecimal cabinPrice1Dec = new BigDecimal(cabinPrice1 != "" ? cabinPrice1 : "0");
    			    	   BigDecimal cabinPrice2Dec = new BigDecimal(cabinPrice2 != "" ? cabinPrice2 : "0");
    			    	   if (cabinPrice1Dec.compareTo(cabinPrice2Dec) > 0) {
    			    		   return 1;
    			    	   } else if (cabinPrice1Dec.compareTo(cabinPrice2Dec) < 0) {
    			    		   return -1;
    			    	   }
    			    	   return 0;
    			      }    
    			     }); 
    			renderData();
				break;
			}
			String fcity = getIntent().getStringExtra("fcity");
			String tcity = getIntent().getStringExtra("tcity");
			StringBuffer sb = new StringBuffer().append("   ").append(fcity).append("至").append(tcity);
			//mTitleInfo.setText(sb);
			super.handleMessage(msg);
		}
	};
	
	public void renderData(){
		data.clear();
		
		for (int j = 0; j < orderist.size(); j++) {
			OrderInfo orderInfo = orderist.get(j);
			List<FlightOrder> FlightTickets = orderInfo.TicketOrders;
			for (int i = 0; i < FlightTickets.size(); i ++) {
				FlightOrder orderDetail = FlightTickets.get(i);
				Map<String, Object> map = new HashMap<String, Object>();
				
				String departureDate = "";
				String departureCity = "";
				String arrivalCity = "";
				String airLine = "";
				System.out.println("orderDetail.FlightID="+orderDetail.FlightID);
				if(orderDetail.FlightID!=null){
					String[] result = orderDetail.FlightID.split(" ");
					airLine = result[2];
					departureCity = addrUtil.getCityByCode(result[0]) != null ? addrUtil.getCityByCode(result[0]).getAirName() : "未知城市";
					arrivalCity = addrUtil.getCityByCode(result[1]) != null ? addrUtil.getCityByCode(result[1]).getAirName() : "未知城市";
					departureDate = result[3];
				}
				System.out.println("orderDetail.Status="+orderDetail.Status);
				System.out.println("orderInfo.Status="+orderInfo.Status);
				
				map.put("departureDate", "行程" + departureDate);
				map.put("departureCity", departureCity);
				map.put("passengerName", orderDetail.PassengerName);
				map.put("arrivalCity", arrivalCity);
				map.put("createTime", "下单" + orderInfo.CreateTime.substring(0,15));
				
//				map.put("tripType", flyUtil.getTripTypeCode(Integer.valueOf(orderDetail.TripType)) + "/" + flyUtil.getItineraryTypeCode(Integer.valueOf(orderDetail.ItineraryType == null || orderDetail.ItineraryType.equals("") ? "0" : orderDetail.ItineraryType)));
				map.put("tripType", flyUtil.getTripTypeCode(Integer.valueOf(orderDetail.TripType)));
				map.put("orderStatus", flyUtil.orderStatusMap.get(orderDetail.Status));
				
				String postFee = String.valueOf(orderDetail.PostFee).equals("") ? "0" : orderDetail.PostFee;
				String insuranceAmount = String.valueOf(orderDetail.InsuranceAmount).equals("") ? "0" : orderDetail.InsuranceAmount;
				float sumPriceV = Float.valueOf(orderDetail.CabinPrice) - Float.valueOf(orderDetail.Rebate) + Float.valueOf(orderDetail.AirportTax) + Float.valueOf(orderDetail.FuelTax) + Float.valueOf(postFee) + Float.valueOf(insuranceAmount);
				map.put("cabinPrice", "￥" + sumPriceV);
				
				map.put("orderInfo", orderInfo);
				map.put("orderDetail", orderDetail);
				data.add(map);
			}
		}
		
		sa = new SimpleAdapter(this, data, R.layout.order_row, new String[] {
				"departureDate", "departureCity", "passengerName", "arrivalCity", "cabinPrice", "orderStatus","tripType"},
				new int[] { R.id.departure_date, R.id.departure_city, R.id.passengerName,
						R.id.arrival_city, R.id.cabin_price, R.id.order_status, R.id.tripType});
		orderList.setAdapter(sa);  
		sa.notifyDataSetChanged();
	}
	
	

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Map<String, Object> item = (Map<String, Object>) orderList.getAdapter().getItem(position);
		OrderInfo orderInfo = (OrderInfo)item.get("orderInfo");
		FlightOrder orderDetail = (FlightOrder)item.get("orderDetail");
		String orderState = orderInfo.TicketOrders.get(0).Status;
		
		Intent intent = new Intent();
		
		if ("1".equalsIgnoreCase(orderState)) {
			intent.setClass(this, OrderDetailPayed.class);
			OrderDetailPayed.ORDER_INFO = orderInfo;
			OrderDetailPayed.ORDER_DETAIL = orderDetail;
			OrderDetailPayed.orderist = orderist;
		} else if ("2".equalsIgnoreCase(orderState)) {
			intent.setClass(this, OrderDetailOutTicket.class);
			OrderDetailOutTicket.ORDER_INFO = orderInfo;
			OrderDetailOutTicket.ORDER_DETAIL = orderDetail;
			OrderDetailOutTicket.orderist = orderist;
		} else if ("11".equalsIgnoreCase(orderState)) {
			intent.setClass(this, OrderDetailOutTicket.class);
			OrderDetailOutTicket.ORDER_INFO = orderInfo;
			OrderDetailOutTicket.ORDER_DETAIL = orderDetail;
			OrderDetailOutTicket.orderist = orderist;
		} else {
			intent.setClass(this, OrderDetail.class);
			OrderDetail.ORDER_INFO = orderInfo;
			OrderDetail.ORDER_DETAIL = orderDetail;
			OrderDetail.orderist = orderist;
		}
		
		startActivity(intent);
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	private void search() {
    	final String ticketNoValue = "";
		
		ContentValues values = new ContentValues();
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询订单中...",true);
		final Thread thread1 = new Thread() {
			public void run() {
				if(searchOrder == null){
					searchOrder = new SearchOrder();
				}
				
				sp = getSharedPreferences("UserInfoB2C", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
		        String userIdLogin = sp.getString("userId", null);
		        Log.i("OrderSearch userIdLogin", userIdLogin);
		        String userPwd =  sp.getString("userPwd", null);
		        Log.i("OrderSearch userPwd", userPwd);
		        
				OrderInfoResult orderInfoResult =  WebAccessor.searchOrderInfo(OrderList.this, searchOrder,userIdLogin,userPwd);
				
				if (progressDialog.isShowing()) {
					if (orderInfoResult== null) {
						Message msg = new Message();
						msg.what = NORESULT;
						myHandler.sendMessage(msg);
					}else if(!"0".equals(orderInfoResult.Ret_Code)){
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = orderInfoResult.Ret_Msg;
						myHandler.sendMessage(msg);
					}else{
						OrderList.orderist = orderInfoResult.OrderInfos;
						//调用
						Message msg = new Message();
						msg.what = SUCCESS;
						msg.obj = orderInfoResult.Ret_Msg;
						myHandler.sendMessage(msg);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread1.start();
	}
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
	
}
